﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using log4net;
using System.Net;
using href.Utils;

namespace ProjectBuilder
{
    public static class UrlExtension
    {
        public static string LoadXmlUrl(this string url)
        {
            LogManager.GetLogger("UrlExtension").Info("Load " + url);

            Stream stream = null;
            var result = "";
            if (url.StartsWith("http://"))
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                var response = request.GetResponse();
                stream = response.GetResponseStream();
            }
            else
            {
                stream = new FileStream(url, FileMode.Open);
            }

            LogManager.GetLogger("UrlExtension").Info("Loaded " + url);
            using (var reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            stream.Close();
            return result;
        }

        private static Dictionary<string, XmlSerializer> _sers = new Dictionary<string, XmlSerializer>();

        public static T parseUrl<T>(this string url)
        {
            var t = typeof(T);
            var st = t.ToString();

            if (!_sers.ContainsKey(st))
            {
                _sers[st] = new XmlSerializer(t);
            }

            var serializer = _sers[st];
            byte[] byteArray;
            string xmlData = url.LoadXmlUrl();
            if (EncodingTools.IsAscii(xmlData))
                byteArray = Encoding.ASCII.GetBytes(xmlData);
            else
                byteArray = Encoding.UTF8.GetBytes(xmlData);
            var stream = new MemoryStream(byteArray);
            T doc = (T)serializer.Deserialize(stream);
            stream.Close();
            if (doc == null)
            {
                throw new Exception(url +"not parsed. AAAAaaaaaa. You must die");
                var sw = System.IO.File.AppendText(Globals.Project.BasePath + Globals.NotParsingFiles);
                sw.WriteLine(url);
                sw.Close();
            }
            return doc;
        }
    }
}
